'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DashboardLayout } from '@/components/layout/dashboard-layout';
import { AdminGuard } from '@/components/auth/PermissionGuard';
import { formatAddress, formatDate, formatCurrency } from '@/lib/utils';
import { multiChainApi } from '@/lib/multi-chain-api';
import { useChain } from '@/context/ChainContext';
import { web3MiningService, type MiningDetails } from '@/lib/web3-mining';
import { Search, UserCheck, UserX, Eye, Filter, Pickaxe, RefreshCw } from 'lucide-react';

interface User {
  id: string;
  wallet_address: string;
  referral_code: string;
  referred_by?: string;
  pop_level: string;
  total_pos: number;
  total_pop: number;
  qualified_pools: number;
  has_nft: boolean;
  nft_count: number;
  is_active: boolean;
  is_frozen: boolean;
  created_at: string;
  last_login?: string;
}

interface UsersStats {
  total_users: number;
  active_users: number;
  frozen_users: number;
  users_with_nft: number;
  total_staked: number;
}

export default function UsersPage() {
  const { t } = useTranslation('users');
  const { currentChain } = useChain();
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'frozen'>('all');
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [showMiningDetails, setShowMiningDetails] = useState(false);
  const [miningDetails, setMiningDetails] = useState<MiningDetails | null>(null);
  const [loadingMiningDetails, setLoadingMiningDetails] = useState(false);
  const [miningError, setMiningError] = useState<string | null>(null);

  // Fetch users stats
  const { data: stats } = useQuery<UsersStats>({
    queryKey: ['users-stats', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get('/api/v1/admin/users/stats');
      return response.data;
    },
    refetchInterval: 30000, // Refresh every 30 seconds
  });

  // Fetch users list
  const { data: users, isLoading, refetch } = useQuery<User[]>({
    queryKey: ['users', searchTerm, statusFilter, currentChain],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (searchTerm) params.append('search', searchTerm);
      if (statusFilter !== 'all') params.append('status', statusFilter);
      
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(`/api/v1/admin/users?${params}`);
      return response.data;
    },
    refetchInterval: 30000,
  });

  const handleFreezeUser = async (userId: string, freeze: boolean) => {
    try {
      const endpoint = freeze ? 'freeze' : 'unfreeze';
      const client = multiChainApi.getClient(currentChain);
      await client.post(`/api/v1/admin/users/${userId}/${endpoint}`);
      refetch();
    } catch (error) {
      console.error('Error updating user status:', error);
    }
  };

  const fetchMiningDetails = async (userAddress: string) => {
    setLoadingMiningDetails(true);
    setMiningError(null);
    try {
      const details = await web3MiningService.getUserMiningInfo(userAddress);
      setMiningDetails(details);
      setShowMiningDetails(true);
    } catch (error) {
      setMiningError(error instanceof Error ? error.message : 'Failed to fetch mining details');
      console.error('Error fetching mining details:', error);
    } finally {
      setLoadingMiningDetails(false);
    }
  };

  const closeMiningDetails = () => {
    setShowMiningDetails(false);
    setMiningDetails(null);
    setMiningError(null);
  };

  const filteredUsers = users?.filter(user => {
    const matchesSearch = !searchTerm || 
      user.wallet_address.toLowerCase().includes(searchTerm.toLowerCase()) ||
      user.referral_code.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesStatus = statusFilter === 'all' || 
      (statusFilter === 'active' && user.is_active && !user.is_frozen) ||
      (statusFilter === 'frozen' && user.is_frozen);
    
    return matchesSearch && matchesStatus;
  }) || [];

  return (
    <DashboardLayout>
      <AdminGuard>
        <div className="space-y-6">
        {/* Header */}
        <div>
          <h1 className="text-3xl font-bold tracking-tight">{t('title')}</h1>
          <p className="text-muted-foreground">
            {t('subtitle')}
          </p>
        </div>

        {/* Stats Cards */}
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-5">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{t('stats.totalUsers')}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats?.total_users || 0}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{t('stats.activeUsers')}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-green-600">{stats?.active_users || 0}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{t('stats.frozenUsers')}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-red-600">{stats?.frozen_users || 0}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{t('stats.nftHolders')}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-purple-600">{stats?.users_with_nft || 0}</div>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{t('stats.totalStaked')}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatCurrency(stats?.total_staked || 0)}</div>
            </CardContent>
          </Card>
        </div>

        {/* Filters */}
        <Card>
          <CardHeader>
            <CardTitle>{t('list.title')}</CardTitle>
            <CardDescription>{t('list.subtitle')}</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex flex-col sm:flex-row gap-4 mb-6">
              <div className="flex-1 relative">
                <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                <input
                  type="text"
                  placeholder={t('list.searchPlaceholder')}
                  className="w-full pl-10 pr-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
              <div className="flex gap-2">
                <select
                  className="px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value as 'all' | 'active' | 'frozen')}
                >
                  <option value="all">{t('list.filters.allStatus')}</option>
                  <option value="active">{t('list.filters.active')}</option>
                  <option value="frozen">{t('list.filters.frozen')}</option>
                </select>
              </div>
            </div>

            {/* Users Table */}
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b">
                    <th className="text-left p-4">{t('list.table.walletAddress')}</th>
                    <th className="text-left p-4">{t('list.table.referralCode')}</th>
                    <th className="text-left p-4">{t('list.table.popLevel')}</th>
                    <th className="text-left p-4">{t('list.table.totalPos')}</th>
                    <th className="text-left p-4">{t('list.table.nfts')}</th>
                    <th className="text-left p-4">{t('list.table.status')}</th>
                    <th className="text-left p-4">{t('list.table.joined')}</th>
                    <th className="text-left p-4">{t('list.table.actions')}</th>
                  </tr>
                </thead>
                <tbody>
                  {isLoading ? (
                    <tr>
                      <td colSpan={8} className="text-center p-8">
                        {t('list.loading')}
                      </td>
                    </tr>
                  ) : filteredUsers.length === 0 ? (
                    <tr>
                      <td colSpan={8} className="text-center p-8 text-muted-foreground">
                        {t('list.noResults')}
                      </td>
                    </tr>
                  ) : (
                    filteredUsers.map((user) => (
                      <tr key={user.id} className="border-b hover:bg-muted/50">
                        <td className="p-4">
                          <div className="font-mono text-sm">
                            {formatAddress(user.wallet_address)}
                          </div>
                        </td>
                        <td className="p-4">
                          <span className="bg-blue-100 text-blue-800 px-2 py-1 rounded text-sm">
                            {user.referral_code}
                          </span>
                        </td>
                        <td className="p-4">
                          <span className={`px-2 py-1 rounded text-sm ${
                            user.pop_level === 'TS' ? 'bg-purple-100 text-purple-800' :
                            user.pop_level.startsWith('T') ? 'bg-green-100 text-green-800' :
                            'bg-gray-100 text-gray-800'
                          }`}>
                            {user.pop_level}
                          </span>
                        </td>
                        <td className="p-4">{formatCurrency(user.total_pos)}</td>
                        <td className="p-4">
                          <div className="flex items-center gap-2">
                            <span>{user.nft_count}</span>
                            {user.has_nft && (
                              <span className="text-purple-600">💎</span>
                            )}
                          </div>
                        </td>
                        <td className="p-4">
                          <div className="flex items-center gap-1">
                            {user.is_frozen ? (
                              <span className="bg-red-100 text-red-800 px-2 py-1 rounded text-sm">
                                {t('list.status.frozen')}
                              </span>
                            ) : user.is_active ? (
                              <span className="bg-green-100 text-green-800 px-2 py-1 rounded text-sm">
                                {t('list.status.active')}
                              </span>
                            ) : (
                              <span className="bg-gray-100 text-gray-800 px-2 py-1 rounded text-sm">
                                {t('list.status.inactive')}
                              </span>
                            )}
                          </div>
                        </td>
                        <td className="p-4 text-sm text-muted-foreground">
                          {formatDate(user.created_at)}
                        </td>
                        <td className="p-4">
                          <div className="flex items-center gap-2">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => setSelectedUser(user)}
                              title="View user details"
                            >
                              <Eye className="h-3 w-3" />
                            </Button>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => fetchMiningDetails(user.wallet_address)}
                              disabled={loadingMiningDetails}
                              title="View mining details from contract"
                              className="text-purple-600 hover:text-purple-700"
                            >
                              {loadingMiningDetails ? (
                                <RefreshCw className="h-3 w-3 animate-spin" />
                              ) : (
                                <Pickaxe className="h-3 w-3" />
                              )}
                            </Button>
                            {user.is_frozen ? (
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => handleFreezeUser(user.id, false)}
                                className="text-green-600 hover:text-green-700"
                              >
                                <UserCheck className="h-3 w-3" />
                              </Button>
                            ) : (
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => handleFreezeUser(user.id, true)}
                                className="text-red-600 hover:text-red-700"
                              >
                                <UserX className="h-3 w-3" />
                              </Button>
                            )}
                          </div>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>

        {/* User Detail Modal */}
        {selectedUser && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
            <Card className="w-full max-w-2xl max-h-[80vh] overflow-y-auto">
              <CardHeader>
                <CardTitle>{t('details.title')}</CardTitle>
                <CardDescription>
                  {formatAddress(selectedUser.wallet_address)}
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="text-sm font-medium">{t('details.fields.walletAddress')}</label>
                    <div className="font-mono text-sm break-all">
                      {selectedUser.wallet_address}
                    </div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.fields.referralCode')}</label>
                    <div className="text-sm">{selectedUser.referral_code}</div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.fields.popLevel')}</label>
                    <div className="text-sm">{selectedUser.pop_level}</div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.fields.totalPos')}</label>
                    <div className="text-sm">{formatCurrency(selectedUser.total_pos)}</div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.fields.totalPop')}</label>
                    <div className="text-sm">{formatCurrency(selectedUser.total_pop)}</div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.fields.qualifiedPools')}</label>
                    <div className="text-sm">{selectedUser.qualified_pools}</div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.fields.nftCount')}</label>
                    <div className="text-sm">{selectedUser.nft_count}</div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.fields.status')}</label>
                    <div className="text-sm">
                      {selectedUser.is_frozen ? t('list.status.frozen') : 
                       selectedUser.is_active ? t('list.status.active') : t('list.status.inactive')}
                    </div>
                  </div>
                  <div>
                    <label className="text-sm font-medium">{t('details.fields.joined')}</label>
                    <div className="text-sm">{formatDate(selectedUser.created_at)}</div>
                  </div>
                  {selectedUser.last_login && (
                    <div>
                      <label className="text-sm font-medium">{t('details.fields.lastLogin')}</label>
                      <div className="text-sm">{formatDate(selectedUser.last_login)}</div>
                    </div>
                  )}
                  {selectedUser.referred_by && (
                    <div className="col-span-2">
                      <label className="text-sm font-medium">{t('details.fields.referredBy')}</label>
                      <div className="font-mono text-sm">{selectedUser.referred_by}</div>
                    </div>
                  )}
                </div>
                <div className="flex justify-end gap-2 pt-4">
                  <Button variant="outline" onClick={() => setSelectedUser(null)}>
                    {t('details.actions.close')}
                  </Button>
                  {selectedUser.is_frozen ? (
                    <Button
                      onClick={() => {
                        handleFreezeUser(selectedUser.id, false);
                        setSelectedUser(null);
                      }}
                      className="bg-green-600 hover:bg-green-700"
                    >
                      {t('details.actions.unfreezeUser')}
                    </Button>
                  ) : (
                    <Button
                      onClick={() => {
                        handleFreezeUser(selectedUser.id, true);
                        setSelectedUser(null);
                      }}
                      variant="danger"
                    >
                      {t('details.actions.freezeUser')}
                    </Button>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>
        )}

        {/* Mining Details Modal */}
        {showMiningDetails && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
            <Card className="w-full max-w-4xl max-h-[80vh] overflow-y-auto">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Pickaxe className="h-5 w-5" />
                  Contract Mining Details
                </CardTitle>
                <CardDescription>
                  Live data from mining contract: 0xD94bF46aF1Bacc4721C1B321785E24c61DBf58D4
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {miningError ? (
                  <div className="text-center p-8">
                    <div className="text-red-600 font-medium mb-2">Error fetching mining details</div>
                    <div className="text-sm text-muted-foreground mb-4">{miningError}</div>
                    <Button 
                      onClick={() => selectedUser && fetchMiningDetails(selectedUser.wallet_address)}
                      disabled={loadingMiningDetails}
                    >
                      {loadingMiningDetails ? (
                        <>
                          <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                          Retrying...
                        </>
                      ) : (
                        'Retry'
                      )}
                    </Button>
                  </div>
                ) : miningDetails ? (
                  <>
                    {/* Summary Cards */}
                    <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
                      <Card>
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm font-medium">Active Miners</CardTitle>
                        </CardHeader>
                        <CardContent>
                          <div className="text-2xl font-bold">{miningDetails.activeMinerCount}</div>
                        </CardContent>
                      </Card>
                      <Card>
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm font-medium">Raw POS Power</CardTitle>
                        </CardHeader>
                        <CardContent>
                          <div className="text-2xl font-bold">{formatCurrency(parseFloat(miningDetails.rawPOSPower))}</div>
                        </CardContent>
                      </Card>
                      <Card>
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm font-medium">Effective POS Power</CardTitle>
                        </CardHeader>
                        <CardContent>
                          <div className="text-2xl font-bold">{formatCurrency(parseFloat(miningDetails.effectivePOSPower))}</div>
                          <div className="text-xs text-muted-foreground">With NFT Boost</div>
                        </CardContent>
                      </Card>
                      <Card>
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm font-medium">Total Staked</CardTitle>
                        </CardHeader>
                        <CardContent>
                          <div className="text-2xl font-bold">{formatCurrency(parseFloat(web3MiningService.formatWei(miningDetails.totalStaked)))}</div>
                          <div className="text-xs text-muted-foreground">DTV</div>
                        </CardContent>
                      </Card>
                      <Card>
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm font-medium">Accumulated Rewards</CardTitle>
                        </CardHeader>
                        <CardContent>
                          <div className="text-2xl font-bold">{formatCurrency(parseFloat(web3MiningService.formatWei(miningDetails.accumulatedReward)))}</div>
                          <div className="text-xs text-muted-foreground">DTV</div>
                        </CardContent>
                      </Card>
                      <Card>
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm font-medium">NFT Multiplier</CardTitle>
                        </CardHeader>
                        <CardContent>
                          <div className="text-2xl font-bold">{web3MiningService.getNFTMultiplierDisplay(miningDetails.nftMultiplier)}</div>
                          <div className="text-xs text-muted-foreground">Boost Factor</div>
                        </CardContent>
                      </Card>
                      <Card>
                        <CardHeader className="pb-2">
                          <CardTitle className="text-sm font-medium">Last Claim</CardTitle>
                        </CardHeader>
                        <CardContent>
                          <div className="text-sm">{web3MiningService.formatTimestamp(miningDetails.lastClaimTimestamp)}</div>
                          <div className="text-xs text-muted-foreground">{web3MiningService.getTimeSinceLastClaim(miningDetails.lastClaimTimestamp)}</div>
                        </CardContent>
                      </Card>
                    </div>

                    {/* Miners Table */}
                    <div>
                      <h3 className="text-lg font-medium mb-4">Individual Miners</h3>
                      <div className="overflow-x-auto">
                        <table className="w-full border-collapse">
                          <thead>
                            <tr className="border-b">
                              <th className="text-left p-3 font-medium">Type</th>
                              <th className="text-left p-3 font-medium">Mode</th>
                              <th className="text-left p-3 font-medium">Staked Amount</th>
                              <th className="text-left p-3 font-medium">POS Power</th>
                              <th className="text-left p-3 font-medium">Lock Status</th>
                              <th className="text-left p-3 font-medium">Remaining Time</th>
                              <th className="text-left p-3 font-medium">Status</th>
                            </tr>
                          </thead>
                          <tbody>
                            {miningDetails.miners.length === 0 ? (
                              <tr>
                                <td colSpan={7} className="text-center p-8 text-muted-foreground">
                                  No miners found in contract
                                </td>
                              </tr>
                            ) : (
                              miningDetails.miners.map((miner, index) => (
                                <tr key={index} className="border-b hover:bg-muted/50">
                                  <td className="p-3">
                                    <span className={`px-2 py-1 rounded text-sm ${
                                      miner.minerType === 0 ? 'bg-slate-100 text-slate-800' :
                                      miner.minerType === 1 ? 'bg-green-100 text-green-800' :
                                      miner.minerType === 2 ? 'bg-blue-100 text-blue-800' :
                                      miner.minerType === 3 ? 'bg-purple-100 text-purple-800' :
                                      miner.minerType === 4 ? 'bg-orange-100 text-orange-800' :
                                      miner.minerType === 5 ? 'bg-red-100 text-red-800' :
                                      miner.minerType === 6 ? 'bg-pink-100 text-pink-800' :
                                      'bg-gray-100 text-gray-800'
                                    }`}>
                                      {web3MiningService.getMinerTypeName(miner.minerType)}
                                    </span>
                                  </td>
                                  <td className="p-3 text-sm">{web3MiningService.getMiningModeName(miner.miningMode)}</td>
                                  <td className="p-3 font-medium">
                                    {formatCurrency(parseFloat(web3MiningService.formatWei(miner.stakedAmount)))} DTV
                                  </td>
                                  <td className="p-3 font-medium">{formatCurrency(parseFloat(miner.posPower))}</td>
                                  <td className="p-3">
                                    <span className={`px-2 py-1 rounded text-xs ${
                                      miner.lockEndTime === 0 ? 'bg-orange-100 text-orange-800' :
                                      web3MiningService.isMinerExpired(miner.lockEndTime) ? 'bg-green-100 text-green-800' :
                                      'bg-blue-100 text-blue-800'
                                    }`}>
                                      {miner.lockEndTime === 0 ? 'Flexible' :
                                       web3MiningService.isMinerExpired(miner.lockEndTime) ? 'Unlocked' : 'Locked'}
                                    </span>
                                  </td>
                                  <td className="p-3 text-sm">
                                    {web3MiningService.getRemainingLockTime(miner.lockEndTime)}
                                  </td>
                                  <td className="p-3">
                                    <span className={`px-2 py-1 rounded text-xs ${
                                      miner.isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                                    }`}>
                                      {miner.isActive ? 'Active' : 'Inactive'}
                                    </span>
                                  </td>
                                </tr>
                              ))
                            )}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </>
                ) : (
                  <div className="text-center p-8">
                    <RefreshCw className="h-8 w-8 mx-auto mb-4 animate-spin text-muted-foreground" />
                    <div className="text-muted-foreground">Loading mining details from contract...</div>
                  </div>
                )}

                <div className="flex justify-end gap-2 pt-4 border-t">
                  <Button variant="outline" onClick={closeMiningDetails}>
                    Close
                  </Button>
                  {miningDetails && (
                    <Button 
                      onClick={() => selectedUser && fetchMiningDetails(selectedUser.wallet_address)}
                      disabled={loadingMiningDetails}
                    >
                      {loadingMiningDetails ? (
                        <>
                          <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                          Refreshing...
                        </>
                      ) : (
                        <>
                          <RefreshCw className="h-4 w-4 mr-2" />
                          Refresh
                        </>
                      )}
                    </Button>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>
        )}
        </div>
      </AdminGuard>
    </DashboardLayout>
  );
}